import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'
import { DcsModel } from '@/api/manager/dcs/interface'
import { interval, Subject } from 'rxjs'
import { map, startWith, switchMap, take } from 'rxjs/operators'
type StateStore = {
	/**
	 * 是否是dcs
	 */
	isDcs: boolean
	/**
	 * dcs 模式 1-主席，2-自由
	 */
	dcsMode: 0 | 1 | 2
	/**
	 * 列表
	 */
	list: DcsModel[]
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	delMts: (mtKeys: string[]) => void
	tableItemCalling: (mtKey: string) => void
	ws: {
		mcc_dcs_conf_status: (mode: 0 | 1 | 2) => void
	}
}
const initialState: StateStore = {
	isDcs: false,
	dcsMode: 0,
	list: [],
}
const tableItemCalling$ = new Subject()
tableItemCalling$
	.pipe(
		switchMap((mtKey) =>
			interval(2000).pipe(
				map(() => false),
				take(1),
				startWith(true),
				map((isCalling) => {
					const list = useTableDcsStore.getState().list
					let item = list.find((x) => x.mtKey === mtKey)
					if (item) {
						item.status.isCalling = isCalling
					}
					return list
				})
			)
		)
	)
	.subscribe((val) => {
		useTableDcsStore.setState({
			list: [...val],
		})
	})
export const store = createVanilla<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		delMts: (mtKeys) => {
			const list = get().list
			let result = list.filter((x) => !mtKeys.includes(x.mtKey))
			set({ list: result })
		},
		tableItemCalling: (mtKey) => {
			tableItemCalling$.next(mtKey)
		},
		ws: {
			mcc_dcs_conf_status: (mode) => {
				set({ dcsMode: mode, isDcs: mode !== 0 })
			},
		},
	}))
)
export const useTableDcsStore = create(store)
